import appApi from '@/apis/app'
import userApi from '@/apis/user'
// import Cookies from 'js-cookie'

// const uid = Cookies.get('DP_UID')

const types = {
  APP_INIT: 'APP_INIT',
  LOGGED_IN: 'LOGGED_IN',
  LOG_OUT: 'LOG_OUT',
  LOGIN_EXPIRED: 'LOGIN_EXPIRED'
}

const state = {
  ready: false,
  logged_in: false
  // logged_in: uid && uid > 0
}

const actions = {
  async preboot ({ commit }) {
    const logged = await userApi.getLoginStatus()
    logged && commit(types.LOGGED_IN)
  },
  login ({ commit }) {
    commit(types.LOGGED_IN)
  },
  async logout ({ commit }) {
    await userApi.logout()
    commit(types.LOG_OUT)
    // location.reload()
    // router && console.log('output')
    // router.replace('/login')
  },
  async init ({ commit, state }) {
    try {
      const data = await appApi.getSession()
      commit(types.LOGGED_IN)
      commit(types.APP_INIT, data)
    } catch (err) {
      console.log(err)
      // Cookies.remove('DP_UID')
      commit(types.LOGIN_EXPIRED)
    }
  }
}

const mutations = {
  [types.LOGGED_IN] (state) {
    state.logged_in = true
  },
  [types.LOG_OUT] (state) {
    state.logged_in = false
    state.ready = false
    delete state.info
    delete state.user
  },
  [types.LOGIN_EXPIRED] (state) {
    // state.ready = false
    state.logged_in = false
  },
  [types.APP_INIT] (state, payload) {
    // const newState = {
    //   ...state,
    //   ...payload.info,
    //   ready: true,
    //   user: payload.user
    // }
    // state = newState
    state.ready = true
    state.id = payload.info.id
    state.info = payload.info
    state.user = payload.user
  }
}

export default {
  state,
  actions,
  mutations
}
